package com.sl.plugin.step.selenium.form;

import cn.hutool.core.util.StrUtil;
import com.sl.core.engine.meta.impl.AbstractProcessCompDescriptor;
import com.sl.core.engine.step.ProcessCompService;
import com.sl.core.engine.step.impl.AbstractProcessComp;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

import java.time.Duration;
import java.util.List;

/**
 */
public class SeleniumFormComp extends AbstractProcessComp<WebDriver, WebDriver> implements ProcessCompService {

    public SeleniumFormComp(AbstractProcessCompDescriptor abstractProcessCompDescriptor) {
        super(abstractProcessCompDescriptor);
    }

    @Override
    public WebDriver input(WebDriver driver) {
        String keywords = meta.getStrAttr("keywords");
        String cssSelector = meta.getStrAttr("cssSelector");
        WebElement element = waitForSelector(driver, cssSelector, null);
        element.sendKeys(keywords);
        return driver;
    }

    private WebElement waitForSelector(WebDriver driver, String cssSelector, String textContains) {
        WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
        WebElement element = null;
        try {
            if (
                    StrUtil.isBlank(textContains)
            ) {
                element = wait.until(
                        ExpectedConditions.presenceOfElementLocated(By.cssSelector(cssSelector))
                );
            } else {
                element = wait.until((d) -> {
                    List<WebElement> el = d.findElements(By.cssSelector(cssSelector));
                    WebElement webElement = el.stream().filter(v -> {
                        String elementText = v.getText();
                        boolean contains = elementText.contains(textContains);

                        return contains;
                    }).findFirst().orElse(null);
                    return webElement;
                });

            }


        } catch (Exception e) {
            element = waitForSelector(driver, cssSelector, textContains);
        }
        return element;
    }

}
